package com.java.netty.nio.netty.websocket;

import com.java.netty.nio.netty.heardbeat.MyServerHandler;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpServerCodec;
import io.netty.handler.codec.http.websocketx.WebSocketServerProtocolHandler;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import io.netty.handler.stream.ChunkedWriteHandler;
import io.netty.handler.timeout.IdleStateHandler;

/**
 * @Author: Dgg
 * @Date: 2022/1/5 23:30
 */
public class MyServer {
	public static void main(String[] args) {
		EventLoopGroup boosGroup = new NioEventLoopGroup(1);
		EventLoopGroup workerGroup = new NioEventLoopGroup(8);
		try {
			ServerBootstrap serverBootstrap = new ServerBootstrap();
			serverBootstrap.group(boosGroup, workerGroup)
					.channel(NioServerSocketChannel.class)
					.handler(new LoggingHandler(LogLevel.INFO))//在bossgroup 增加 日志处理器
					.childHandler(new ChannelInitializer<SocketChannel>() {
						@Override
						protected void initChannel(SocketChannel ch) throws Exception {
							ChannelPipeline pipeline = ch.pipeline();

							//因为基于http协议，使用http编码解码
							pipeline.addLast(new HttpServerCodec());
							//是以块的方式写，添加chunkedwriteHandler 处理器
							pipeline.addLast(new ChunkedWriteHandler());
							/**
							 *	1.http数据传输过程中是分段的HttpObjectAggregator ， 就是可以将多个端聚合起来
							 * 	2.这就是为什么浏览器发送大量数据时就会发出多次http请求的原因
							 */
							pipeline.addLast(new HttpObjectAggregator(8192));
							/**
							 * 	1.对于websocket 他的数据是以帧（frame） 的形式传递
							 * 	2.可以看到websocketframe有六个子类
							 * 	3.浏览器请求时：ws://localhost:7000/hello 表示请求的uri
							 * 	4.WebSocketServerProtocolHandler他的核心功能时将http协议升级为ws协议，保持长连接。
							 */
							pipeline.addLast(new WebSocketServerProtocolHandler("/hello"));
							//自定义handler，处理业务逻辑
							pipeline.addLast(new MyTextWebSocketFrameHandler());

						}
					});
			ChannelFuture sync = serverBootstrap.bind(7000).sync();
			sync.channel().closeFuture().sync();
		} catch (InterruptedException e) {
			e.printStackTrace();
		} finally {
			boosGroup.shutdownGracefully();
			workerGroup.shutdownGracefully();
		}
	}
}
